import json
import os.path

from kubernetes import client, config
class KubeCli():
    def __init__(self, kubeconfig):
        config.load_kube_config(kubeconfig)

        # 获取API的CoreV1Api版本对象
        #self.v1 = client.CoreV1Api()

    def get_all_deployment_tag(self, namespace):
        apps_v1 = client.AppsV1Api()
        for deployment in apps_v1.list_namespaced_deployment(namespace).items:
            deployment_name = deployment.metadata.name
            deployment_image = deployment.spec.template.spec.containers[0].image
            deployment_tag = deployment_image.split(':')[-1]
            print(deployment_name, deployment_tag)

    def get_pod_tag(self, namespace, deployment):
        core_v1 = client.CoreV1Api()
        datas = {}
        for item in core_v1.list_namespaced_pod(namespace, label_selector='app=leaf-server').items:

            pod_name = item.metadata.name
            pod_status = item.status.phase
            pod_start_time = item.status.start_time
            image = item.spec.containers[0].image
            pod_tag = image.split(':')[-1]
            datas[pod_name] = {
                'image': image,
                'tag': pod_tag,
                'status': pod_status,
                'start_time': pod_start_time.strftime('%Y-%m-%d %H:%M:%S')
            }
        print(json.dumps(datas, indent=4))
        return datas

    def get_all_namespaces(self):
        v1 = client.AppsV1Api()
        for ns in v1.list_namespace().items:
            print(ns.metadata.name)


if __name__ == '__main__':
    from pathlib import Path

    BASE_DIR = Path(__file__).resolve().parent
    print(BASE_DIR)
    kubeconfig = os.path.join(BASE_DIR, '../.kube/aliyun-hlwyy-dev-config')
    kubecli = KubeCli(kubeconfig=kubeconfig)
    # kubecli.get_all_deployment_tag(namespace='cobra')
    kubecli.get_pod_tag(namespace='cobra', deployment='')